#include "clkDirectInput.h"

clkDirectInput::clkDirectInput()
{
	m_diObject = 0;
	m_diKeyboard = 0;
	m_diMouse = 0;
	m_diPrevKey = 0;
	m_diPrevButton = 0;
	memset(m_diKeyboardState,0,sizeof(m_diKeyboardState));
	memset(&m_diMouseState,0,sizeof(DIMOUSESTATE));
}

clkDirectInput::~clkDirectInput()
{
	shutDirectInput();
}

void clkDirectInput::initDirectInput(HWND a_hwnd, HINSTANCE a_hInstance)
{
	m_diHwnd = a_hwnd;

	DirectInput8Create(a_hInstance,DIRECTINPUT_VERSION,
		IID_IDirectInput8,(void**)&m_diObject,0);

	m_diObject->CreateDevice(GUID_SysKeyboard,&m_diKeyboard,0);
	m_diObject->CreateDevice(GUID_SysMouse,&m_diMouse,0);

	m_diKeyboard->SetDataFormat(&c_dfDIKeyboard);
	m_diMouse->SetDataFormat(&c_dfDIMouse);

	m_diKeyboard->SetCooperativeLevel(a_hwnd,
		DISCL_NONEXCLUSIVE|DISCL_FOREGROUND);
	m_diMouse->SetCooperativeLevel(a_hwnd,
		DISCL_NONEXCLUSIVE|DISCL_FOREGROUND);
}

void clkDirectInput::shutDirectInput()
{
	if(m_diKeyboard){m_diKeyboard->Unacquire();}
	if(m_diMouse){m_diMouse->Unacquire();}
}

void clkDirectInput::acquire()
{
	m_diKeyboard->Acquire();
	m_diMouse->Acquire();

	memset(m_diKeyboardState,0,sizeof(m_diKeyboardState));
	memset(&m_diMouseState,0,sizeof(m_diMouseState));

	//m_diPrevKeys.clear();
	//m_diPrevButtons.clear();

	m_diKeyboard->GetDeviceState(256,(LPVOID)m_diKeyboardState);
	m_diMouse->GetDeviceState(sizeof(DIMOUSESTATE),(LPVOID)&m_diMouseState);
}

bool clkDirectInput::keyInput(int a_key)
{
	return (m_diKeyboardState[a_key] & 0x80)?true:false;
}

bool clkDirectInput::keyPress(int a_key, bool a_ignore)
{
	if(m_diKeyboardState[a_key] & 0x80)
	{
		if(a_ignore)
			return true;

		int i = 0;
		for(i = 0; i < (int)m_diPrevKeys.size(); i++)
			if(a_key == m_diPrevKeys[i])
				return false;
		m_diPrevKeys.push_back(a_key);
		return true;
	}
	for(int i = 0; i < (int)m_diPrevKeys.size(); i++)
		if(a_key == m_diPrevKeys[i])
			m_diPrevKeys.erase(m_diPrevKeys.begin()+i);
	return false;
}

bool clkDirectInput::mouseInput(int a_button)
{
	return (m_diMouseState.rgbButtons[a_button] & 0x80)?true:false;
}

bool clkDirectInput::mousePress(int a_button)
{
	if(m_diMouseState.rgbButtons[a_button] & 0x80)
	{
		int i = 0;
		for(i = 0; i < (int)m_diPrevButtons.size(); i++)
			if(a_button == m_diPrevButtons[i])
				return false;
		m_diPrevButtons.push_back(a_button);
		return true;
	}
	for(int i = 0; i < (int)m_diPrevButtons.size(); i++)
		if(a_button == m_diPrevButtons[i])
			m_diPrevButtons.erase(m_diPrevButtons.begin()+i);
	return false;
}

V3DF clkDirectInput::mouseDelta()
{
	return V3DF(
		(float)m_diMouseState.lX,
		(float)m_diMouseState.lY,
		(float)m_diMouseState.lZ);
}

V2DF clkDirectInput::mousePosition()
{
	POINT cursor;
	GetCursorPos(&cursor);
	ScreenToClient(m_diHwnd,&cursor);
	return V2DF(
		(float)cursor.x,
		(float)cursor.y);
}